package client

import (
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/metrics/pkg/client/clientset/versioned"
)

type K8sClientSet struct {
	Client        *kubernetes.Clientset
	MetricsClient *versioned.Clientset
}

// 加载配置文件，生成config
func (k *K8sClientSet) Config() (config *rest.Config, err error) {
	// 优先在集群内部加载
	config, err = rest.InClusterConfig()
	if err != nil {
		// 在集群内部加载失败，则从集群外部加载
		config, err = clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
		if err != nil {
			panic(err.Error())
		}
	}
	return
}

func (k *K8sClientSet) GetClientset() (*kubernetes.Clientset, error) {
	cfg, err := k.Config()
	if err != nil {
		return nil, err
	}
	return kubernetes.NewForConfig(cfg)
}

func (k *K8sClientSet) GetMetricsClientset() (*versioned.Clientset, error) {
	cfg, err := k.Config()
	if err != nil {
		return nil, err
	}
	return versioned.NewForConfig(cfg)
}
